<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>简单散点图</title>
  <script type="text/javascript" src="http://d3js.org/d3.v5.min.js"></script>
  <script src="../js/d3.tip.js"></script>
</head>

<body>
  <svg width="1200" height="600"></svg>
</body>

<script>
  const svg = d3.select("svg");
  const width = svg.attr("width");
  const height = svg.attr("height");
  const margin = { left: 60, top: 60, right: 60, bottom: 60 };
  const innerWidth = width - margin.right - margin.left;
  const innerHeight = height - margin.top - margin.bottom;

  const data = [
    [5, 66],
    [7, 55],
    [4, 99],
    [11, 78],
    [28, 65],
    [7, 88],
    [5, 56],
    [2, 60],
    [4, 57],
    [6, 98],
    [27, 33],
    [26, 77],
    [23, 95],
    [34, 87],
    [7, 68],
    [1, 68],
    [2, 60],
    [22, 84],
    [6, 96],
    [13, 87]
  ]

  const maingroup = svg.append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  /**
     * 提示 
     */
  let tip = d3.tip() // 设置tip
    .attr('class', 'd3-tip')
    .offset([-10, 0])
    .html(function (d) {
      return (
        '<div style="background:grey;color:#ffffff;padding:10px;line-height:25px">' +
        '<strong>运动年限:</strong> <span style="color:#ffeb3b">' + d[0] + '</span><br>' +
        '<strong>健康指数:</strong> <span style="color:#ffeb3b">' + d[1] + '</span>' +
        '</div>'
      )
    })

  maingroup.call(tip)

  /**
   *  x轴 + y轴
   */
  const xScale = d3.scaleLinear()
    .domain([0, d3.max(data, d => d[0])])
    .range([0, innerWidth]);

  const yScale = d3.scaleLinear()
    .domain([0, d3.max(data, d => d[1])])
    .range([innerHeight, 0]);

  maingroup.append("g")
    .attr("class", "xAxis")
    .attr("transform", "translate(0," + innerHeight + ")")
    .call(d3.axisBottom(xScale))
    .append("text")
    .attr("x", innerWidth)
    .attr("y", 40)
    .attr("fill", "black")
    .attr("text-anchor", "end")
    .attr("font-size", "14px")
    .text("激烈运动年限 (年)")

  maingroup.append("g")
    .attr("class", "yAxis")
    .call(d3.axisLeft(yScale))
    .append("text")
    .attr("y", -10)
    .attr("fill", "black")
    .attr("text-anchor", "start")
    .attr("font-size", "14px")
    .text("健康指数 (分)")


  /**
   * 散点
   */
  const colorScale = d3.scaleOrdinal(d3.schemePaired);
  maingroup.append("g")
    .attr("class", "point-g")
    .selectAll("circle")
    .data(data)
    .enter()
    .append("circle")
    .on("mouseover", tip.show)
    .on("mouseout", tip.hide)
    .attr("fill", d => {
      return colorScale(d[1])
    })
    .attr("cx", d => xScale(d[0]))
    .attr("cy", d => yScale(d[1]))
    .attr("r", 0)
    .transition()
    .duration(750)
    .delay(function (d, i) {
      return i * 10
    })
    .attr("r", 10)



</script>

</html>
